import { loginAPI, getInfoAPI, getAvatarAPI } from '@/api'
import { getToken, setToken, removeToken, setTokenTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state() {
    return {
      token: getToken(),
      userInfo: {}
    }
  },
  actions: {
    async logIn(context, data) {
      const res = await loginAPI(data)
      context.commit('setToken', res)
      setTokenTimeStamp()
    },

    // 获取用户资料
    async getUserInfo(context) {
      const res = await getInfoAPI()
      // 获取用户头像
      const baseInfo = await getAvatarAPI(res.userId)
      context.commit('setUserInfo', { ...res, ...baseInfo })
      return res
    },
    // 登出删除用户信息
    logout(contex) {
      contex.commit('removeToken')
      contex.commit('removeUserInfo')
      resetRouter()
      contex.commit('permission/changeRoutes', [], { root: true })
    }
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, payload) {
      state.userInfo = payload
    },
    removeUserInfo(state) {
      state.userInfo = {}
    }
  }
}
